package com.abel.bigwater.dataserver.model.ewide

import com.abel.bigwater.data.BcdString
import com.abel.bigwater.model.JsonHelper
import com.alibaba.fastjson.annotation.JSONField
import io.netty.buffer.ByteBuf
import java.util.*

class TermBurstData(_pduLen: Int = -1) : TermData(KmingDataType.TermBurst, _pduLen) {
    /**
     * 起始时间 6 BCD 终端采样时间：年-月-日-时-分-秒（注
    2）
     */
    var startTimeStr: BcdString? = null

    var deviceStatus: DeviceStatus? = null

    /**
     * 时间对象
     */
    @JSONField(format = JsonHelper.FULL_DATE_FORMAT)
    private var _startTime: Date? = null

    var startTime: Date?
        get() {
            _startTime = if (startTimeStr == null) null else startTimeStr!!.toFullYearTime()
            return _startTime
        }
        set(value) {
            _startTime = value
            startTimeStr = if (_startTime == null) null
            else TermData.fromFullYearTime(_startTime!!)
        }

    override fun bufLength() = 1 + 7 + 3

    override fun parseBuf(buf: ByteBuf): Boolean {
        buf.apply {
            assert(type == KmingDataType.findByCode(readUnsignedByte()))

            startTimeStr = BcdString.create(this, 7)

            deviceStatus = DeviceStatus().also { it.parseBuf(this) }
        }

        return true
    }

    override fun pack(buf: ByteBuf) {
        assert(7 == startTimeStr!!.size)

        buf.alloc().buffer().apply {
            writeByte(type.code.toInt())

            writeBytes(startTimeStr!!.hexArray)

            deviceStatus!!.pack(this)

            buf.writeBytes(this)
        }
    }
}